package com.b2b.controller;

import com.alibaba.fastjson.JSONObject;
import com.b2b.exception.CustomException;
import com.b2b.exception.CustomUnauthorizedException;
import com.b2b.model.UserDto;
import com.b2b.model.common.ResponseBean;
import com.b2b.model.entity.SMS;
import com.b2b.model.entity.User;
import com.b2b.service.CompanyUserRoleService;
import com.b2b.service.UserService;
import com.b2b.util.CompanyRoleUtil;
import com.b2b.util.SMSUtil;
import com.b2b.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@RestController
@CrossOrigin
@RequestMapping("/safe")
@PropertySource("classpath:config.properties")
public class SafeController {


    @Value("${refreshTokenExpireTime}")
    private String refreshTokenExpireTime;

    private final UserUtil userUtil;

    private final UserService userService;

    private final CompanyUserRoleService companyUserRoleService;

    @Autowired
    public SafeController(UserUtil userUtil, UserService userService, CompanyUserRoleService companyUserRoleService) {
        this.userUtil = userUtil;
        this.userService = userService;
        this.companyUserRoleService = companyUserRoleService;
    }

    /**
     * 更新用户
     * @param userDto
     * @return java.util.Map<java.lang.String,java.lang.Object>
     * @author dolyw.com
     */
    @PutMapping("/updateBaseDate")
    public ResponseBean updateBase(@RequestBody UserDto userDto) {
        UserDto userDtoTemp = new UserDto();
        userDtoTemp.setUserId(userDto.getUserId());
        int count = userService.selectCount(userDtoTemp);
        if (count<=0) {
            throw new CustomUnauthorizedException("该帐号不存在(Account not exist.)");
        }
        count = userService.updateByPrimaryKeySelective(userUtil.getBaseUser(userDto));
        if (count <= 0) {
            throw new CustomException("更新失败(Update Failure)");
        }
        return new ResponseBean(HttpStatus.OK.value(), "更新成功(Update Success)", userDto);
    }

    @PostMapping("/updatePassword")
    public ResponseBean updatePassword(@RequestBody Map<String,Object> userDate){
        if (!userDate.containsKey("userId")){
            throw new CustomException("更新失败(Update Failure)");
        }
        String oldPassword = userDate.get("oldPassword").toString();
        String newPassword = userDate.get("newPassword").toString();
        Integer userId = Integer.parseInt(userDate.get("userId").toString());
        User user = userService.selectByPrimaryKey(userId);
        if (!user.getPassword().equals(oldPassword)){
            throw new CustomException("原密码错误! 更新失败(Update Failure)");
        }
        user.setPassword(newPassword);
        Integer count = userService.updateByPrimaryKeySelective(user);
        return new ResponseBean(HttpStatus.OK.value(), "更新成功(Update Success)", null);
    }

    @PutMapping("/updatePhone/sendSMS")
    public ResponseBean updatePhoneS(HttpServletRequest request, @RequestBody SMS sms){
        String phone = sms.getPhone();
        Integer min = 3;
        sms.setMin(min);
        sms.setTemplateId(1109984);
        if(phone==null && phone.equals("")){
            throw new CustomUnauthorizedException("号码为空(Phone Null.)");
        }
        User userTemp = new User();
        userTemp.setPhone(phone);
        Integer count = userService.selectCount(userTemp);
        if (count <= 0) {
            throw new CustomUnauthorizedException("该电话不存在(Phone NotExist.)");
        }
        String s = SMSUtil.sendSMS(request,sms);
        return new ResponseBean(HttpStatus.OK.value(), "发送成功(Send Success)", s);
    }

    @PutMapping("/updatePhone/checkSMS")
    public ResponseBean updatePhoneC(HttpServletRequest request, @RequestBody SMS sms){
        String code = sms.getCode();
        JSONObject json = (JSONObject)request.getSession().getAttribute("MsCode");
        if(!json.getString("Code").equals(code)){
            throw new CustomUnauthorizedException("验证码错误(Code Error.)");
        }
        if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 3){
            throw new CustomUnauthorizedException("验证码过期(Code expire.)");
        }
        //将用户信息存入数据库
        User user = userService.selectByPrimaryKey(sms.getUserId());
        user.setPhone(sms.getPhone());
        int count = userUtil.insertNewUser(user);
        if (count <= 0){
            throw new CustomException("新增失败(Insert Failure)");
        }
        return new ResponseBean(HttpStatus.OK.value(), "新增成功(Send Success)", user);
    }
}
